package vip.meeet.jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;


public class DBHelper {

    public static void batchAdd(Connection connection, List<String> sqls, int batchSize) throws SQLException {
        if (sqls.size() <= batchSize) {
            batchAdd(connection,sqls);
        }
        int trun = sqls.size() / batchSize;
        List<String> subSqls;
        for (int i = 0; i < trun; i++) {
            subSqls = sqls.subList(i * batchSize, (i + 1) * batchSize);
            batchAdd(connection,subSqls);
        }
        if(sqls.size() % batchSize != 0){
            subSqls = sqls.subList(trun * batchSize,sqls.size());
            batchAdd(connection,subSqls);
        }
    }

    public static void batchAdd(Connection connection, List<String> sqls) throws SQLException {
        Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        connection.setAutoCommit(false);
        if (sqls == null || sqls.size() == 0) {
            return;
        }
        for (String sql : sqls) {
            statement.addBatch(sql);
        }
        statement.executeBatch();
        connection.commit();
        connection.setAutoCommit(true);
    }

    /**
     * 只有一个String字段
     * @param connection
     * @param sql
     * @return
     * @throws SQLException
     */
    public static List<String> getStringList(Connection connection,String sql) throws SQLException {
        Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery(sql);
        ArrayList<String> results = new ArrayList<>();
        while (rs.next()){
            results.add(rs.getString(1));
        }
        return results;
    }

    public static boolean executeDDL(String db, String sql) throws SQLException {
        Connection ddlConnection = ConnectionHelper.getDDLConnection(db);
        Statement statement = ddlConnection.createStatement();
        return statement.execute(sql);
    }
}
